var pageNo = 1;
var pageSize = 10;
const app = getApp();
var url = app.data.url;
var picRoot = app.data.picRoot; 
var util = require('../../utils/util.js');
import Dialog from '@vant/weapp/dialog/dialog';
var map = new Map();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    currentTab: 0,
    merchantName: '',
    cart: [],
    merchantId: '',
    itemTypeList: [],
    queryType: 0,
    typeNum: 0,
    typeShow: false,
    menuShow: false,
    menuTypeId: '',
    menuTypeName: '',
    fileList: [],
    fileSavePath: '',
    radio: '0',
    itemClassify: '',
    itemName: '',
    itemDesc: '',
    itemPrice: '',
    itemDiscountPrice: '',
    itemMenuType: '',
    itemNum: '',
    putAwayStatus: true,
    popBtn: 0,
    itemId: '',
    overLayShow: false,
    typeName:'',
    specStatus: false,
    detailShow: false
  },
  /**
   * 跳转设置规格页面
   */
  setSpec: function(option){
    console.log(option);
    let _that = this;
    let itemId = option.currentTarget.dataset.id;
    let merchantId = _that.data.merchantId;
    let title = option.currentTarget.dataset.title;
    wx.navigateTo({
      url: '../../pages/item-detail/index?merchantId=' + merchantId + '&itemId=' + itemId + '&title=【' + title +'】商品规格',
    })
  },
  /**
   * 新增菜单
   */
  insertOrUpdateMenu: function(option) {
    let _that = this;
    let itemName = _that.data.itemName;
    let itemDesc = _that.data.itemDesc;
    let itemPrice = _that.data.itemPrice;
    let itemDiscountPrice = _that.data.itemDiscountPrice;
    let fileSavePath = _that.data.fileSavePath;
    let radio = _that.data.radio;
    let merchantId = _that.data.merchantId;
    let itemClassify = _that.data.itemClassify;
    let putAwayStatus = _that.data.putAwayStatus;
    let method = option.currentTarget.dataset.method;
    let itemNum = _that.data.itemNum;
    let specStatus = _that.data.specStatus;
    let temp = 0;

    if (putAwayStatus) {
      temp = 0;
    } else {
      temp = 1;
    }
    let tempUrl = (method == 0 ? url + "/ItemSystemApi/insertItem" : url + "/ItemSystemApi/updateItem");
    let tempData = ''
    if (method == 0) {
      tempData = {
        merchantId: merchantId,
        itemClassify: itemClassify,
        name: itemName,
        description: itemDesc,
        picPath: fileSavePath,
        price: itemPrice,
        discountPrice: itemDiscountPrice,
        payType: radio,
        putAwayStatus: temp,
        createUserName: app.globalData.uuid,
        number: itemNum,
        activeSpecStatus: specStatus == true?'Y':'N'
      }
    } else {
      let itemId = _that.data.itemId
      tempData = {
        id: itemId,
        merchantId: merchantId,
        itemClassify: itemClassify,
        name: itemName,
        description: itemDesc,
        picPath: fileSavePath,
        price: itemPrice,
        discountPrice: itemDiscountPrice,
        payType: radio,
        putAwayStatus: temp,
        updateUserName: app.globalData.uuid,
        number: itemNum,
        activeSpecStatus: specStatus == true ? 'Y' : 'N'
      }
    }

    wx.request({
      url: tempUrl,
      data: tempData,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res);
        if (res.data.code == 200) {
          // 重新加载
          _that.queryData(merchantId);
          _that.setData({
            menuShow: false
          })
          wx.showToast({
            title: "操作成功!",
            icon: "success",
            duration: 3000
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 3000
          })
        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })

  },
  putaway: function(options) {
    let _that = this;
    let id = options.currentTarget.dataset.id;
    let title = options.currentTarget.dataset.title;
    let merchantId = _that.data.merchantId;
    let putAwayStatus = options.currentTarget.dataset.status;

    let temp = putAwayStatus == 0 ? "1" : "0";
    wx.request({
      url: url + '/ItemSystemApi/setPutAwayStatus',
      data: {
        id: id,
        status: temp
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 200) {
          // 重新加载
          _that.queryData(merchantId);
          wx.showToast({
            title: "操作成功!",
            icon: "success",
            duration: 3000
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 3000
          })
        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })
  },
  batchPutAway: function(options) {

  },
  deleteItem: function(options) {
    let _that = this;
    let id = options.currentTarget.dataset.id;
    let title = options.currentTarget.dataset.title;
    let merchantId = _that.data.merchantId;
    Dialog.confirm({
      title: '提醒',
      message: '是否确定删除【' + title + "】"
    }).then(() => {
      // on confirm
      wx.request({
        url: url + '/ItemSystemApi/deleteItem',
        data: {
          id: id
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.code == 200) {
            // 重新加载
            _that.queryData(merchantId);
            wx.showToast({
              title: "删除成功!",
              icon: "success",
              duration: 3000
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
            })
          }
        },
        fail: function(res) {
          console.info('submit fail');
        },
        complete: function(res) {
          console.info('submit complete');
        }
      })
    }).catch(() => {
      // on cancel
    });

  },
  /**表单onChange start */
  specStatusChange: function (event) {
    let _that = this;
    _that.setData({
      specStatus: event.detail
    });
  },
  onItemNumChange: function(event) {
    let _that = this;
    _that.setData({
      itemNum: event.detail
    });
  },
  onPutAwayStatusChange: function(event) {
    let _that = this;
    _that.setData({
      putAwayStatus: event.detail
    });
  },
  /**
   * 菜单类型
   */
  onMenuTypeChange: function(event) {
    let _that = this;
    _that.setData({
      itemMenuType: event.detail
    });
  },
  /**
   * 折扣价
   */
  onDiscountPriceChange: function(event) {
    let _that = this;
    _that.setData({
      itemDiscountPrice: event.detail
    });
  },
  /**
   * 原价
   */
  onPriceChange: function(event) {
    let _that = this;
    _that.setData({
      itemPrice: event.detail
    });
  },
  /**
   * 菜品描述
   */
  onItemDescChange: function(event) {
    let _that = this;
    _that.setData({
      itemDesc: event.detail
    });
  },
  /**
   * 菜品名称
   */
  onItemNameChange: function(event) {
    let _that = this;
    _that.setData({
      itemName: event.detail
    });
  },
  onRadioChange: function(event) {
    let _that = this;
    _that.setData({
      radio: event.detail
    });
  },
  /**表单onChange end */

  /**
   * 删除图片
   */
  deleteImg: function(option) {
    let _that = this;
    Dialog.confirm({
      title: '是否删除',
      message: '删除后请点击编辑按钮保存!'
    }).then(() => {
      // on confirm
      let saveImg = _that.data.fileSavePath;      
      wx.request({
        url: url + '/ItemSystemApi/insertDeleteImg',
        data: {
          img: saveImg
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.code == 200) {
            // 重新加载
            let {
              fileList = []
            } = _that.data;
            fileList.splice(option.detail.index, 1);
            _that.setData({
              fileList: fileList,
              fileSavePath: ''
            });
            _that.queryData(merchantId);
            wx.showToast({
              title: "删除成功!",
              icon: "success",
              duration: 3000
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
            })
          }
        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })
    

    }).catch(() => {
      // on cancel
    });
    
  },
  /**
   * 上传图片
   */
  afterRead(event) {
    let _that = this;
    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    _that.onOverLayShow();
    wx.uploadFile({
      url: url + '/ItemSystemApi/uploadPic',
      filePath: file.path,
      header: {
        "Content-Type": "multipart/form-data"
      },
      name: 'file',
      success(res) {
        if (res.statusCode == 200) {
          // 上传成功
          const {
            fileList = []
          } = _that.data;
          fileList.push({ ...file,
            url: picRoot + res.data
          });
          _that.setData({
            fileList
          });
          _that.setData({
            fileSavePath: res.data
          })
          _that.onOverLayHide();
        } else {
          wx.showToast({
            title: "上传失败!",
            icon: "none",
            duration: 2000
          })
        }
      }
    });
  },
  switchNav: function(e) {
    console.log(e);
    var page = this;
    var id = e.target.id;
    let title = e.currentTarget.dataset.title;
    let menuTypeId = e.currentTarget.dataset.menutypeid;
    let itemClassify = e.currentTarget.dataset.itemclassify;

    page.setData({
      active: id,
      menuTypeName: title,
      menuTypeId: menuTypeId,
      itemClassify: itemClassify
    });

    if (this.data.currentTab == id) {
      return false;
    } else {
      page.setData({
        currentTab: id
      });
    }

  },

  // 菜单弹框 start
  editMenu: function(options) {
    console.log(options);
    // 回显
    let _that = this;
    let id = options.currentTarget.dataset.id;
    let title = options.currentTarget.dataset.title;
    let price = options.currentTarget.dataset.price;
    let discountprice = options.currentTarget.dataset.discountprice;
    let payType = options.currentTarget.dataset.paytype + "";
    let desc = options.currentTarget.dataset.desc;
    let img = options.currentTarget.dataset.img;
    let putAwayStatus = options.currentTarget.dataset.status;
    let saveImg = options.currentTarget.dataset.saveimage;
    let num = options.currentTarget.dataset.num;
    let itemTypeList = _that.data.itemTypeList;
    let activeType = itemTypeList[_that.data.active];
    let specStatus = options.currentTarget.dataset.spec;
    console.log(specStatus);

    // 回显一张图片
    let fileList = [];
    fileList.push({
      url: img
    });

    _that.setData({
      menuShow: true,
      popBtn: 1,
      fileSavePath: saveImg,
      radio: payType,
      itemName: title,
      itemDesc: desc,
      itemPrice: price,
      itemDiscountPrice: discountprice,
      putAwayStatus: putAwayStatus == 0 ? true : false,
      specStatus: specStatus == 'Y'? true: false,
      itemId: id,
      fileList: fileList,
      itemNum: num,
      typeName: activeType.title
    });
  },
  /**弹框 */
  onOverLayShow() {
    this.setData({
      overLayShow: true
    });
  },
  onOverLayHide() {
    this.setData({
      overLayShow: false
    });
  },
  addMenu: function(options) {
    let _that = this;
    let itemTypeList = _that.data.itemTypeList;
    let activeType = itemTypeList[_that.data.active];
    _that.setData({
      menuShow: true,
      fileSavePath: '',
      radio: '0',
      itemName: '',
      itemDesc: '',
      itemPrice: '',
      itemDiscountPrice: '',
      putAwayStatus: true,
      itemId: '',
      fileList: [],
      menuShow: true,
      popBtn: 0,
      itemMenu: '',
      typeName: activeType.title
    });
  },
  onMenuClose: function() {
    this.setData({
      menuShow: false
    });
  },
  saveMenu: function(e) {
    let _that = this;
    let merchantId = _that.data.merchantId;

  },
  onChangeMenu: function(option) {
    let value = option.detail;
    let _that = this;
    _that.setData({
      menuTypeName: value
    })
  },
  // 菜单弹框 end


  // 菜单类型弹框 start
  editType: function(options) {
    let _that = this;
    let menuTypeName = _that.data.menuTypeName;
    _that.setData({
      typeShow: true,
      popBtn: 1,
      menuTypeName: menuTypeName
    });
  },
  addType: function(options) {
    let _that = this;
    _that.setData({
      typeShow: true,
      popBtn: 0
    });
  },
  onTypeClose: function() {
    this.setData({
      typeShow: false
    });
  },
  /**
   * 删除分类
   */
  batchDelete: function(options) {
    let _that = this;
    let title = _that.data.menuTypeName;
    let itemClassify = _that.data.itemClassify;
    let merchantId = _that.data.merchantId;
    let menuTypeId = _that.data.menuTypeId;
    Dialog.confirm({
      title: "提醒:是否确定删除分类【" + title + "】",
      message: '该操作会同时批量删除该分类下所有单品, 请慎重确定!'
    }).then(() => {
      // on confirm
      wx.request({
        url: url + '/ItemSystemApi/batchDelete',
        data: {
          merchantId: merchantId,
          itemClassify: itemClassify,
          menuTypeId: menuTypeId,
          createUserName: app.globalData.uuid
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.code == 200) {
            // 重新加载
            _that.queryData(merchantId);
            wx.showToast({
              title: "删除成功!",
              icon: "success",
              duration: 3000
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
            })
          }
        },
        fail: function(res) {
          console.info('submit fail');
        },
        complete: function(res) {
          console.info('submit complete');
        }
      })
    }).catch(() => {
      // on cancel
    });
  },
  /**
   * 保存或者修改分类
   */
  saveOrEditMenuType: function(e) {
    let _that = this;
    let merchantId = _that.data.merchantId;
    let name = _that.data.menuTypeName;
    let menuTypeId = _that.data.menuTypeId;
    let popBtn = _that.data.popBtn;

    let tempUrl = (popBtn == 0 ? url + '/ItemSystemApi/insertMenuType' : url + '/ItemSystemApi/updateMenuType')
    let tempData;
    if (popBtn == 0) {
      tempData = {
        merchantId: merchantId,
        title: name,
        createUserUuid: app.globalData.uuid
      }
    } else {
      tempData = {
        title: name,
        menuTypeId: menuTypeId,
        createUserUuid: app.globalData.uuid,
      }
    }

    // 保存菜单类型
    wx.request({
      url: tempUrl,
      data: tempData,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 200) {
          // 重新加载菜单类型
          _that.queryData(merchantId);
          _that.setData({
            typeShow: false
          })
          wx.showToast({
            title: "操作成功!",
            icon: "success",
            duration: 2000
          })
        } else {
          wx.showToast({
            title: res.data.data,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })


  },
  onChangeMenuType: function(option) {
    let value = option.detail;
    let _that = this;
    _that.setData({
      menuTypeName: value
    })
  },
  // 菜单类型弹框 end

  onLoad: function(option) {
    console.log(option);
    var merchantId = option.merchantId;
    wx.setNavigationBarTitle({
      title: "商品管理"
    })
    let _that = this;
    _that.setData({
      merchantId: merchantId
    })
    // 查询菜品分类
    _that.queryData(merchantId);
  },
  /**
   * 加载菜单数据
   */
  queryData: function(merchantId) {
    let that = this;
    wx.request({
      url: url + '/ItemSystemApi/queryItemListByMerchantId',
      data: {
        merchantId: merchantId
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 200) {
          // 设置菜单分类是否点击, 0是未点击，1是点击
          console.log(res.data.data);
          if (res.data.data.length > 0) {
            let title = res.data.data[0].title;
            let menyTypeId = res.data.data[0].menuTypeId;
            let classifyType = res.data.data[0].classifyType
            that.setData({
              itemTypeList: res.data.data,
              menuTypeId: menyTypeId,
              menuTypeName: title,
              itemClassify: classifyType
            })

            // 加载默认选中的菜单
            wx.request({
              url: url + '/ItemSystemApi/queryItemByMerchantIdAndItemTypeId',
              data: {
                pageNo: pageNo,
                pageSize: pageSize,
                merchantId: merchantId
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(res) {
                if (res.data.code == 200) {
                  console.log(res.data.data);
                  that.setData({
                    cart: res.data.data,
                    typeNum: res.data.data.length
                  })
                } else {
                  wx.showToast({
                    title: res.data.msg,
                    icon: "fail",
                    duration: 2000
                  })
                }

              },
              fail: function(res) {
                console.info('submit fail');
              },
              complete: function(res) {
                console.info('submit complete');
              }
            })
          } else {
            wx.showToast({
              title: '当前商铺尚未设置菜单, 请先添加分类',
              icon: "none",
              duration: 2000
            })
          }

        } else {
          wx.showToast({
            title: '当前商铺尚未设置菜单, 请先添加分类',
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function(res) {
        console.info('submit fail1');
      },
      complete: function(res) {
        console.info('submit complete1');
      }
    })
  },
  /**
   * 上拉触底加载更多数据
   */
  onReachBottom: function() {

  },

  /**
   * 监听用户下拉动作(下拉刷新)
   */
  onPullDownRefresh: function() {},

})